package com.wxdc.nmgyt.nmgytwydc.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.just.agentwebX5.AgentWebX5;
import com.just.agentwebX5.ChromeClientCallbackManager;
import com.just.agentwebX5.DefaultWebClient;
import com.just.agentwebX5.DownLoadResultListener;
import com.just.agentwebX5.MiddleWareWebChromeBase;
import com.just.agentwebX5.MiddleWareWebClientBase;
import com.just.agentwebX5.PermissionInterceptor;
import com.just.agentwebX5.WebDefaultSettingsManager;
import com.just.agentwebX5.WebSettings;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebView;
import com.wxdc.nmgyt.nmgytwydc.R;
import com.wxdc.nmgyt.nmgytwydc.agentweb.base.widget.WebLayout;
import com.wxdc.nmgyt.nmgytwydc.common.MyCommon;
import com.wxdc.nmgyt.nmgytwydc.presenter.BaseWebX5Persenter;
import com.wxdc.nmgyt.nmgytwydc.presenter.contract.BaseWebX5Contract;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * Created by Administrator on 2018/5/14.
 */

public abstract class BaseWebX5Activity extends BaseActivity<BaseWebX5Persenter> implements BaseWebX5Contract.View {


    private final String TAG = this.getClass().getSimpleName();
    protected AgentWebX5 mAgentWebX5;
    private AlertDialog mAlertDialog;
    private MiddleWareWebClientBase mMiddleWareWebClient;
    private MiddleWareWebChromeBase mMiddleWareWebChrome;
    protected abstract int getLayout();

    private TextView toolBarTitle;//标题栏 标题内容
    // private DownloadingService mDownloadingService;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayout());

    }

    protected void initAgentWeb(ViewGroup viewGroup, TextView toolBarTitle, String httpUrl) {
        this.toolBarTitle = toolBarTitle;
        long p = System.currentTimeMillis();
        if (mAgentWebX5 == null) {
            mAgentWebX5 = AgentWebX5.with(this)
                    .setAgentWebParent(viewGroup, new LinearLayout.LayoutParams(-1, -1))
                    .useDefaultIndicator()//
                    .defaultProgressBarColor()
                    .setReceivedTitleCallback(mCallback)
                    .setWebChromeClient(mWebChromeClient)
                    .setWebViewClient(mWebViewClient)
                    .useMiddleWareWebChrome(getMiddleWareWebChrome())
                    .useMiddleWareWebClient(getMiddleWareWebClient())
                    .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                    .interceptUnkownScheme()
                    .setSecutityType(AgentWebX5.SecurityType.strict)
                    .setNotifyIcon(R.mipmap.download)
                    .setPermissionInterceptor(mPermissionInterceptor)
                    .addDownLoadResultListener(mDownLoadResultListener)
                    .setWebLayout(new WebLayout(this))
                    .createAgentWeb()
                    .ready()
                    .go(httpUrl);
        } else {
            mAgentWebX5.getLoader().loadUrl(httpUrl);
        }
        long n = System.currentTimeMillis();
        Log.i("Info", "init used time:" + (n - p));
        Log.i(TAG, "initAgentWeb: ------------>"+httpUrl);
    }


    private com.tencent.smtt.sdk.WebViewClient mWebViewClient = new com.tencent.smtt.sdk.WebViewClient() {
        @Override
        public void onPageStarted(com.tencent.smtt.sdk.WebView view, String url, Bitmap favicon) {
            //do you  work
            Log.i("Info", "BaseWebActivity onPageStarted");
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest) {
            FileInputStream input;
            String url = webResourceRequest.getUrl().toString();

            Log.i(TAG, "shouldInterceptRequest------拦截的url："+url);;
            String key = "http://androidimg";
                /*如果请求包含约定的字段 说明是要拿本地的图片*/
            if (url.contains(key)) {
                //String imgPath = url.replace(key, "");
                String imgPath = url.substring(0,url.lastIndexOf("?")).replace(key,"");
                Log.i(TAG,"本地图片路径：" + imgPath.trim());
                try {
                    Log.i(TAG, "shouldInterceptRequest: -------ddd----->"+ URLDecoder.decode(imgPath,"utf-8"));
                    imgPath = URLDecoder.decode(imgPath, "utf-8");//URL解码
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                try {
                        /*重新构造WebResourceResponse  将数据已流的方式传入*/
                    input = new FileInputStream(new File(imgPath.trim()));
                    WebResourceResponse response = new WebResourceResponse("image/jpg", "UTF-8", input);
                        /*返回WebResourceResponse*/
                    return response;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();

                }

            }
            return super.shouldInterceptRequest(webView, webResourceRequest);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String s) {
            mAgentWebX5.getLoader().loadUrl(s);
            return super.shouldOverrideUrlLoading(webView, s);
        }

        @Override
        public void onPageFinished(WebView webView, String s) {
            // 在结束加载网页时会回调
            Log.i(TAG, "onPageFinished: --------------------"+s);
            super.onPageFinished(webView, s);
        }
    };
    private com.tencent.smtt.sdk.WebChromeClient mWebChromeClient = new com.tencent.smtt.sdk.WebChromeClient() {

        @Override
        public void onProgressChanged(com.tencent.smtt.sdk.WebView webView, int i) {
            super.onProgressChanged(webView, i);

        }

      /*  @Override
        public void onReceivedTitle(com.tencent.smtt.sdk.WebView webView, String title) {
            super.onReceivedTitle(webView, title);
            if (toolBarTitle != null && !TextUtils.isEmpty(title)) {
                if (title.length() > 15) {
                    title = title.substring(0, 15).concat("...");
                }
            }
            toolBarTitle.setText(title);
        }*/

    };
    private ChromeClientCallbackManager.ReceivedTitleCallback mCallback = new ChromeClientCallbackManager.ReceivedTitleCallback() {
        @Override
        public void onReceivedTitle(com.tencent.smtt.sdk.WebView view, String title) {
            if (toolBarTitle != null)
                toolBarTitle.setText(title);
        }
    };

    /**
     * 用于方便打印测试
     */
    private Gson mGson = new Gson();
    //2993.4 1909.1
    //3363 1781 | 2802 1837|2461 2663| 4943 2843|2714 1526|3183 1780|2669 1630|2780 1704|2870 1562|2779 1565|2997 1862|
    protected PermissionInterceptor mPermissionInterceptor = new PermissionInterceptor() {

        //AgentWeb 在触发某些敏感的 Action 时候会回调该方法， 比如定位触发 。
        //例如 https//:www.baidu.com 该 Url 需要定位权限， 返回false ，如果版本大于等于23 ， agentWeb 会动态申请权限 ，true 该Url对应页面请求定位失败。
        //该方法是每次都会优先触发的 ， 开发者可以做一些敏感权限拦截 。
        @Override
        public boolean intercept(String url, String[] permissions, String action) {
            Log.i(TAG, "url:" + url + "  permission:" + mGson.toJson(permissions) + " action:" + action);
            return false;
        }
    };
    protected DownLoadResultListener mDownLoadResultListener = new DownLoadResultListener() {
        @Override
        public void success(String path) {

            Log.i("Info", "path:" + path);
            /*File mFile=new File(path);
            mFile.delete();*/
        }

        @Override
        public void error(String path, String resUrl, String cause, Throwable e) {

            Log.i("Info", "path:" + path + "  url:" + resUrl + "  couse:" + cause + "  Throwable:" + e);
        }
    };

    public WebSettings getSettings() {
        return WebDefaultSettingsManager.getInstance();
    }

    public String getUrl() {

        return "https://m.jd.com/";
    }

    protected void showDialog() {

        if (mAlertDialog == null) {
            mAlertDialog = new AlertDialog.Builder(this)
                    .setMessage("您确定要关闭该页面吗?")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (mAlertDialog != null) {
                                mAlertDialog.dismiss();
                            }
                        }
                    })//
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            if (mAlertDialog != null) {
                                mAlertDialog.dismiss();
                            }
                            BaseWebX5Activity.this.finish();
                        }
                    }).create();
        }
        mAlertDialog.show();

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mAgentWebX5.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        mAgentWebX5.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWebX5.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mAgentWebX5.uploadFileResult(requestCode, resultCode, data);
        Log.i("Info", "onResult:" + requestCode + " onResult:" + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //mAgentWeb.destroy();
        mAgentWebX5.getWebLifeCycle().onDestroy();

    }

    /**
     * MiddlewareWebClientBase 是 AgentWeb 3.0.0 提供一个强大的功能，
     * 如果用户需要使用 AgentWeb 提供的功能， 不想重写 WebClientView方
     * 法覆盖AgentWeb提供的功能，那么 MiddlewareWebClientBase 是一个
     * 不错的选择 。
     *
     * @return
     */

    public MiddleWareWebChromeBase getMiddleWareWebChrome() {
        return mMiddleWareWebChrome;
    }

    public MiddleWareWebClientBase getMiddleWareWebClient() {
        return mMiddleWareWebClient;
    }
}
